package com.gable.exhibition.controller;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.CacheData;
import com.gable.common.util.ImportExcel;
import com.gable.common.util.ReturnResultUtil;
import com.gable.common.util.StringUtil;
import com.gable.exhibition.model.User;
import com.gable.exhibition.service.ManufacturerService;
import com.gable.exhibition.util.CheckImportExcelHospital;
import com.gable.exhibition.util.CheckImportExcelManufacturer;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Lesson on 2018/1/4.
 */
@Controller
@RequestMapping(value="/manufacturer")
public class ManufacturerController {

    Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    ManufacturerService manufacturerService;

    @Autowired
    CheckImportExcelManufacturer checkImportExcelManufacturer;

    @RequestMapping(value="/page")
    public String page(HttpServletRequest request, HttpServletResponse response){
        return "manufacturer/manufacturer-page";
    }


    @RequestMapping(value="/queryManufacturerList",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryManufacturerList(HttpServletRequest request, HttpServletResponse response,ManufacturerView manufacturerView){
        try{
            ReturnResultUtil rru = manufacturerService.queryManufacturerList(manufacturerView);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
    }


    @RequestMapping(value="/addOrUpdateManufacturer",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil addOrUpdateManufacturer(HttpServletRequest request, HttpServletResponse response,ManufacturerView manufacturerView) {
        try{
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Long userId = null;

            if(!StringUtil.isEmpty(request.getParameter("userId"))){
                userId = Long.parseLong(request.getParameter("userId"));
            }
            UserView user = CacheData.getSessionUser(userId, 1);
            if(manufacturerView.getManufacturerId() == null){
                manufacturerView.setCreatePerson(user.getUserId());
                manufacturerView.setCreateTime(df.format(new Date()));
            }else{
                manufacturerView.setUpdatePerson(user.getUserId());
                manufacturerView.setUpdateDate(df.format(new Date()));
            }
            return manufacturerService.addOrUpdateManufacturer(manufacturerView);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500, MessageUtil.SAVEEXCEPTION);
    }

    @RequestMapping(value="/queryManufacturerInfo",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryManufacturerInfo(HttpServletRequest request, HttpServletResponse response,Long manufacturerId) {

        try{
            ReturnResultUtil rru = manufacturerService.queryManufacturerInfo(manufacturerId);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
    }
    @RequestMapping(value="/import")
    public String importManufacturer(HttpServletRequest request, HttpServletResponse response){

        return "manufacturer/manufacturer-import";

    }


    @RequestMapping(value="/manufacturerExcel",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil manufacturerExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("files");
        String rootPath = request.getSession().getServletContext().getRealPath(File.separator);
        try {
            Long ym = new Date().getTime();
            String filePath = "upload/" + ym;
            if (files != null && files.size() > 0) {
                for (MultipartFile m : files) {
                    if (m.getBytes().length == 0) {
                        return new ReturnResultUtil(500, MessageUtil.PLEASEUPLOADFILE);
                    }
                    String suffix = m.getOriginalFilename().substring(m.getOriginalFilename().lastIndexOf(".") + 1);
                    if (!suffix.equals("xlsx")) {
                        return new ReturnResultUtil(500, MessageUtil.FILEFORMATWRONG);
                    }
                    filePath = filePath + suffix;
                    File file = new File(rootPath + filePath);
                    if (file.exists()) {
                        file.delete();
                        file.mkdirs();
                    } else {
                        file.mkdirs();
                    }
                    m.transferTo(file);
                }
                User user = CacheData.getSessionUser(null,1);
                List<Object> list = ImportExcel.excelRead(rootPath + filePath, CheckImportExcelManufacturer.properties, ImportExcelManufacturerModel.class);
                CheckImportExcelManufacturer.resultMap.put(user.getUserId(), list);
                logger.info("==================" + JSON.toJSONString(list));
                return new ReturnResultUtil(200, MessageUtil.UPLOADSUCCESS, list);

            } else {
                return new ReturnResultUtil(500, MessageUtil.UPLOADFILESERROR);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  new ReturnResultUtil(500,MessageUtil.UPLOADEXCEPTION);
    }


    @RequestMapping(value="/checkExcelManufacturer",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil checkExcelManufacturer(HttpServletRequest request, HttpServletResponse response){
        ImportExcelView importExcelView = new ImportExcelView();
        try {
            User user = CacheData.getSessionUser(null,1);
            List<ImportExcelManufacturerModel> list =(List<ImportExcelManufacturerModel>)CheckImportExcelManufacturer.resultMap.get(user.getUserId());
            importExcelView = checkImportExcelManufacturer.checkManufacturer(list);
            return new ReturnResultUtil(200,MessageUtil.EXAMINESUCCESS,importExcelView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.EXAMINEERROR);
    }

    @RequestMapping(value="/saveManufacturerByExecl",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil saveManufacturerByExecl(HttpServletRequest request, HttpServletResponse response){
        try {
            User user = CacheData.getSessionUser(null, 1);
            List<ImportExcelManufacturerModel> list = (List<ImportExcelManufacturerModel>) CheckImportExcelManufacturer.resultMap.get(user.getUserId());
            ReturnResultUtil rru = manufacturerService.saveManufacturerByExcel(list,user);
            CheckImportExcelManufacturer.resultMap.remove(user.getUserId());
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }



    @RequestMapping(value="/queryManufacturerListBymainId",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryManufacturerListBymainId(HttpServletRequest request, HttpServletResponse response){

        try{
            if(StringUtil.isEmpty(request.getParameter("maintainerId"))){
                return new ReturnResultUtil(500,MessageUtil.MAINTAINERIDISNULL);
            }

            Long maintainerId = Long.parseLong(request.getParameter("maintainerId"));
            ReturnResultUtil rru = manufacturerService.queryManufacturerListBymainId(maintainerId);
            logger.info(JSON.toJSONString(rru));
            return  rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
    }

    @RequestMapping(value="/bindMaintainerInit",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil bindMaintainerInit(HttpServletRequest request, HttpServletResponse response, MaintainerView maintainerView ){

        try{
            if(maintainerView.getManufacturerId() == null){
                return new ReturnResultUtil(500,MessageUtil.MANUFACTURERIDISNULL);
            }
            ReturnResultUtil rru = manufacturerService.bindMaintainerInit(maintainerView);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
    }

    @RequestMapping(value="/saveSetMaintainer",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil saveSetMaintainer(HttpServletRequest request, HttpServletResponse response ){
        try {
            if (StringUtil.isEmpty(request.getParameter("manufacturerId"))) {
                return new ReturnResultUtil(500, MessageUtil.MANUFACTURERIDISNULL);
            }

            if (StringUtil.isEmpty(request.getParameter("maintainerIds"))) {
                return new ReturnResultUtil(500, MessageUtil.MAINTAINERIDISNULL);
            }

            Long manufacturerId = Long.parseLong(request.getParameter("manufacturerId"));
            String[] maintainerIds = request.getParameter("maintainerIds").split(",");
            List<Long> maintainerIdList = new ArrayList<Long>();
            for (String str : maintainerIds) {
                maintainerIdList.add(Long.parseLong(str));
            }
            ReturnResultUtil rru = manufacturerService.saveSetMaintainer(maintainerIdList,manufacturerId);
            return  rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return  new ReturnResultUtil(500, MessageUtil.SAVEEXCEPTION);
    }

    @RequestMapping(value="/queryManufacturerListBySuppId",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryManufacturerListBySuppId(HttpServletRequest request, HttpServletResponse response){
        try{
            if(StringUtil.isEmpty(request.getParameter("supplierId"))){
                new ReturnResultUtil(500,MessageUtil.SUPPLIERIDISNULL);
            }
            Long supplierId = Long.parseLong(request.getParameter("supplierId"));
            ReturnResultUtil rru = manufacturerService.queryManufacturerListBySuppId(supplierId);
            logger.debug(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
    }


    @RequestMapping(value="/bindSupplierInit",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil bindSupplierInit(HttpServletRequest request, HttpServletResponse response, SupplierView supplierView ){

        try{
            if(supplierView.getManufacturerId() == null){
                return new ReturnResultUtil(500,MessageUtil.MANUFACTURERIDISNULL);
            }
            ReturnResultUtil rru = manufacturerService.bindSupplierInit(supplierView);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
    }


    @RequestMapping(value="/saveSetSupplier",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil saveSetSupplier(HttpServletRequest request,HttpServletResponse response){
        try {
            if (StringUtil.isEmpty(request.getParameter("manufacturerId"))) {
                return new ReturnResultUtil(500, MessageUtil.MANUFACTURERIDISNULL);
            }

            if (StringUtil.isEmpty(request.getParameter("supplierIds"))) {
                return new ReturnResultUtil(500, MessageUtil.SUPPLIERIDISNULL);
            }

            Long manufacturerId = Long.parseLong(request.getParameter("manufacturerId"));
            String[] supplierIds = request.getParameter("supplierIds").split(",");
            List<Long> supplierIdList = new ArrayList<Long>();
            for (String str : supplierIds) {
                supplierIdList.add(Long.parseLong(str));
            }
            ReturnResultUtil rru = manufacturerService.saveSetSupplier(supplierIdList,manufacturerId);
            return  rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return  new ReturnResultUtil(500, MessageUtil.SAVEEXCEPTION);
    }
}
